package com.atguigu.tingshu;

import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceAlbumApplication implements CommandLineRunner {
    // 预热布隆过滤器
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private AlbumInfoService albumInfoService;
    public static void main(String[] args) {
        SpringApplication.run(ServiceAlbumApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // 初始化布隆过滤器
        // 查询数据库中的数据，判断是否需要初始化布隆过滤器
        String bloomFilterKey = RedisConstant.ALBUM_BLOOM_FILTER;
        // 查询数据库
        List<Long> albumIdList = albumInfoService.list(new LambdaQueryWrapper<AlbumInfo>().select(AlbumInfo::getId)).stream().map(AlbumInfo::getId).toList();
        boolean bloomFilter = redissonClient.getBloomFilter(bloomFilterKey).tryInit(albumIdList.size(), 0.03);
        if (bloomFilter) {
            // 初始化布隆过滤器
            albumIdList.forEach(albumId -> redissonClient.getBloomFilter(bloomFilterKey).add(albumId));
        }
    }
}
